package com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools

import android.content.Context
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Chronometer
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.base.App
import java.math.BigDecimal
import java.text.DecimalFormat

/*
 * auther: 王国龙
 * Date：2020.05.17
 * describe:实现一些常用方法
* */
object LancooMethod {

    fun View.addClickScale() {
        this.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    this.animate().scaleX(1.1f).scaleY(1.1f).setDuration(200).start()
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    this.animate().scaleX(1f).scaleY(1f).setDuration(200).start()
                }
            }
            // 点击事件处理，交给View自身
            this.onTouchEvent(event)
        }
    }

    fun getNewItemAnalysis(itemAnalysis: String): String {
        var ItemAnalysis = itemAnalysis
        if(ItemAnalysis.isEmpty()){
            ItemAnalysis = App.instance().resources.getString(R.string.aibk_no_text)
        }
        return ItemAnalysis
    }

    fun getNewItemAnswer(itemAnswer: String, isTkt: Boolean): String {
        var itemAnswer = itemAnswer
        itemAnswer = itemAnswer.replace("\\$、".toRegex(), "、")
        itemAnswer = itemAnswer.replace("\\$/".toRegex(), "或")
        if (isTkt) {
            itemAnswer = itemAnswer.replace("\\'".toRegex(), "\\\\\\'")
        }
        return itemAnswer
    }

    fun getNewStuAnswer(itemAnswer: String, isTkt: Boolean): String {
        var itemAnswer = itemAnswer
        if (isTkt) {
            itemAnswer = itemAnswer.replace("\\'".toRegex(), "\\\\\\'")
        }
        return itemAnswer
    }

    /*
   * 将int型转化为Ascii
   * @param str
   * */
    open fun intToAscii(i: Int): Char {
        val c = i.toChar()
        return c
    }

    /**
     * 判断str1中包含str2的个数
     * @param str
     * @param key
     * @return counter
     */
    open fun getKeyCount(str: String, key: String): Int {

        var index = 0 //定义变量。记录每一次找到的key的位置。
        var count = 0 //定义变量，记录出现的次数。

//定义循环。只要索引到的位置不是-1，继续查找。
        while (UnitMoreSpan(str)!!.indexOf(key, index).also { index = it } != -1) {
            //每循环一次，就要明确下一次查找的起始位置。
            index = index + key.length
            //每查找一次，count自增。
            count++
        }
        return count
    }

    /*
    * 正则表达式，将一个字符串中的多个连一起的空格变成单个空格
    * */
    open fun UnitMoreSpan(str: String): String? {
        return str.replace("\\s{1,}".toRegex(), " ")
    }

    /*
     * 对double数据 进行去除没用的.0
     * */
    fun killlingDouble(value: Double): String? {
        val b = value.toInt()
        return if (value == b.toDouble()) {
            b.toString()
        } else {
            value.toString()
        }
    }

    /**
     * 减法：a-b
     * 去掉ss小数点后面多余的0
     */
    //    0.0500
    fun DeleteRMBZero(a: Double, b: Double): String? {
        val b1 = BigDecimal(a.toString())
        val b2 = BigDecimal(b.toString())
        var ss = b1.subtract(b2).toString()

        for (i in ss.indices) {
            ss = if (ss.substring(ss.length - 1) == "0") {
                ss.substring(0, ss.length - 1)
            } else {
                return ss
            }
        }
        return ss
    }


    //    String numbers = "1|2|3|4|5";
    ////    使用split拆分
    //    String[] numberArray = numbers.split("\\| ");
    /*
     * @Title 输出一个字符串数组
     * @param AllString 需要拆解的字符窜
     * @param thisString 需要判断的字符
     * @param i_begin 分隔符所占的字符数
     * */
    fun returnArray(
            allString: String,
            thisString: String?,
            i_begin: Int
    ): Array<String?>? {
        var count = 0
        val i_strArrayflag = getStringFrequency(allString, thisString)
        val strArray = arrayOfNulls<String>(i_strArrayflag + 1)
        var strA = allString
        while (strA.indexOf(thisString!!) != -1) {
            count++
            strArray[count - 1] = strA.substring(0, strA.indexOf(thisString))
            //将字符串出现c的位置之前的全部截取掉
            strA = strA.substring(strA.indexOf(thisString) + i_begin)
        }
        strArray[count] = strA
        printArray(strArray)
        return strArray
    }

    /*
     *@Title//判断某个字符在整个字符串中出现的次数、频率
     *@param allString：整个字符串
     *@param thisString：需要判断的字符
     * */
    fun getStringFrequency(allString: String, thisString: String?): Int {
        var count = 0
        var str = allString //你要测试的字符串
        str = str.toLowerCase() //将字符串全部转化成小写//考虑大小写：
        //index为字符串中第一次出现c的位置，如果字符串中没有c将返回-1
        val index = str.indexOf(thisString!!)
        //如果字符串中有c
        while (str.indexOf(thisString) != -1) {
            count++
            str = str.substring(str.indexOf(thisString) + 1)
        }
        return count
    }

    //输出数组
    fun printArray(array: Array<String?>) {
        for (i in array.indices) {
            print("" + i + "====yyyyy==" + array[i])
            if (i == array.size - 1) {
                print("\n")
            } else {
                print(",")
            }
        }
    }

    fun getHours(second: Long): String? { //计算秒有多少小时
        var h: Long = 0
        val temp = second % (3600 * 24)
        if (second > 3600 * 24) {
            if (temp != 0L) {
                h = temp / 3600
            }
        } else {
            h = second / 3600
        }
        return h.toString() + ""
    }

    fun getMins(second: Long): String? { //计算秒有多少分
        var m: Long = 0
        val temp = second % 3600
        if (second > 3600) {
            if (temp != 0L) {
                if (temp > 60) {
                    m = temp / 60
                }
            }
        } else {
            m = second / 60
        }
        return m.toString() + ""
    }

    fun getSeconds(second: Long): String? { //计算秒有多少秒
        var s: Long = 0
        val temp = second % 3600
        if (second > 3600) {
            if (temp != 0L) {
                if (temp > 60) {
                    if (temp % 60 != 0L) {
                        s = temp % 60
                    }
                } else {
                    s = temp
                }
            }
        } else {
            if (second % 60 != 0L) {
                s = second % 60
            }
        }
        return s.toString() + ""
    }

    /*
     * 计时器换算
     * */
    fun getChronometerTime(cmt: Chronometer): Int? {
        /**
         *
         * @param cmt  Chronometer控件
         * @return 小时+分钟+秒数  的所有秒数
         */
        var totals = 0
        val string = cmt.text.toString()
        if (string.length >= 7) {
            val split = string.split(":").toTypedArray()
            val string2 = split[0]
            val hour = string2.toInt()
            val Hours = hour * 3600
            val string3 = split[1]
            val min = string3.toInt()
            val Mins = min * 60
            val SS = split[2].toInt()
            totals = Hours + Mins + SS
            return totals
        } else if (string.length == 5) {
            val split = string.split(":").toTypedArray()
            val string3 = split[0]
            val min = string3.toInt()
            val Mins = min * 60
            val SS = split[1].toInt()
            totals = Mins + SS
            return totals
        }
        return totals
    }

    /**
     * 数字转汉字【新】
     *
     * @param num
     * @return
     */
    private val nums = arrayOf("零", "一", "二", "三", "四", "五", "六", "七", "八", "九")
    private val pos_units = arrayOf("", "十", "百", "千")
    private val weight_units = arrayOf("", "万", "亿")
    fun numberToChinese(num: Int): String? {
        var num = num
        if (num == 0) {
            return "零"
        }
        var weigth = 0 //节权位
        var chinese = ""
        var chinese_section = ""
        var setZero = false //下一小节是否需要零，第一次没有上一小节所以为false
        while (num > 0) {
            val section = num % 10000 //得到最后面的小节
            if (setZero) { //判断上一小节的千位是否为零，是就设置零
                chinese = nums[0] + chinese
            }
            chinese_section = sectionTrans(section)
            if (section != 0) { //判断是都加节权位
                chinese_section = chinese_section + weight_units[weigth]
            }
            chinese = chinese_section + chinese
            chinese_section = ""
            Log.d("TAG", chinese_section)
            setZero = section < 1000 && section > 0
            num = num / 10000
            weigth++
        }
        if ((chinese.length == 2 || chinese.length == 3) && chinese.contains("一十")) {
            chinese = chinese.substring(1, chinese.length)
        }
        if (chinese.indexOf("一十") == 0) {
            chinese = chinese.replaceFirst("一十".toRegex(), "十")
        }
        return chinese
    }

    /**
     * 将每段数字转汉子
     * @param section
     * @return
     */
    fun sectionTrans(section: Int): String {
        var section = section
        val section_chinese = StringBuilder()
        var pos = 0 //小节内部权位的计数器
        var zero = true //小节内部的置零判断，每一个小节只能有一个零。
        while (section > 0) {
            val v = section % 10 //得到最后一个数
            if (v == 0) {
                if (!zero) {
                    zero = true //需要补零的操作，确保对连续多个零只是输出一个
                    section_chinese.insert(0, nums[0])
                }
            } else {
                zero = false //有非零数字就把置零打开
                section_chinese.insert(0, pos_units[pos])
                section_chinese.insert(0, nums[v])
            }
            pos++
            section = section / 10
        }
        return section_chinese.toString()
    }

    //小数点后两位四舍五入
    fun formatDouble(d: Double, newScale: Int): Double {
        val bigDecimal = BigDecimal(d)
        return bigDecimal.setScale(newScale, BigDecimal.ROUND_HALF_UP).toDouble()
    }

    fun getCorrectRateInt(small: Double, big: Int): Double {
        val size = small / big
        val df = DecimalFormat("0.00") //格式化小数，不足的补0
        return java.lang.Double.valueOf(df.format(size))
    }

    fun getCorrectRate(small: Double, big: Double): Double {
        val size = small / big
        val df = DecimalFormat("0.00") //格式化小数，不足的补0
        return java.lang.Double.valueOf(df.format(size))
    }

    //乘以100并四舍五入保留4位小数(分值占比专用)
    fun getScoreRate(v: Double, scale: Int): String {
        require(scale >= 0) { "The scale must be a positive integer or zero" }
        val b: BigDecimal = if (null == v) BigDecimal("0.0") else BigDecimal(java.lang.Double.toString(v))
        val one = BigDecimal("1")
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).toString()+"%"
    }

    fun getBusiness(small: Int, big: Int): Float {
        val size = small*100 / big
        val df = DecimalFormat("0.00") //格式化小数，不足的补0
        return java.lang.Double.valueOf(df.format(size)).toFloat()
    }

    fun showRoundImageView(context: Context,iv:ImageView,resourceId:Int,roundingRadius:Int, width:Int, height:Int){
        val options= RequestOptions()
                .override(width,height)
                .fitCenter() //注意要设置这个
                .transform(RoundedCorners( roundingRadius))
                .dontAnimate()
        Glide.with(context)
                .load(resourceId)
                .apply(options)
                .into(iv)
    }

}